package com.baizhi.config;

import com.baizhi.filter.AccessControlAllowFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Configuration//该类是一个配置类，替换spring的配置文件
public class MyConfig implements WebMvcConfigurer {
    @Bean
    public FilterRegistrationBean filterRegist() {
        //管理过滤器的一个管理类，我们把自己的过滤交个这个类进行注册管理
        FilterRegistrationBean frBean = new FilterRegistrationBean();
        frBean.setFilter(new AccessControlAllowFilter());
        frBean.addUrlPatterns("/*");//过滤都有一个url-pattern
        return frBean;
    }

    //配置缓存管理器
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory){

        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);

        return new RedisCacheManager(redisCacheWriter,getRedisCacheConfiguration(20),
                getRedisCacheConfigurationMap());
    }

    private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap(){
        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
        //以NewsServiceImpl开头的缓存要存储100秒
        redisCacheConfigurationMap.put("NewsServiceImpl", getRedisCacheConfiguration(100));
        return redisCacheConfigurationMap;
    }
    //RedisCacheConfiguration 用于负责Redis的缓存配置
    private RedisCacheConfiguration getRedisCacheConfiguration(int seconds){
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        return redisCacheConfiguration
                .serializeValuesWith(
                        RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)
                )
                .entryTtl(Duration.ofSeconds(seconds));
    }
}
